#include <wiringPi.h>
#include <stdio.h>  
#include <sys/time.h> 

#define Trig_pin 29     // 定义 排针的第40引脚接 模块的发射引脚
#define Echo_pin 28  // 定义 排针的第38引脚接模块的接收引脚

// 系统和管脚初始化
void systemInit(){
    wiringPiSetup();
    // 初始化发射引脚
    pinMode (Trig_pin, OUTPUT);
    // 初始化接收引脚
    pinMode (Echo_pin, INPUT);
}
// 测量 距离
float getDis(){
    struct timeval start_time;
    struct timeval stop_time;

    digitalWrite (Trig_pin, LOW); delay(10);
    digitalWrite (Trig_pin, HIGH);
    delayMicroseconds(10);
    digitalWrite (Trig_pin, LOW);

    while(!(digitalRead(Echo_pin) == 1));      
    gettimeofday(&start_time, NULL);           //获取当前时间 开始接收到返回信号的时候       while(!(digitalRead(Echo) == 0));      gettimeofday(&tv2, NULL);           //获取当前时间  最后接收到返回信号的时候

    while(!(digitalRead(Echo_pin) == 0));      
    gettimeofday(&stop_time, NULL);

    float start, stop;
    start = start_time.tv_sec * 1000000 + start_time.tv_usec;   //微秒级的时间  
    stop  = stop_time.tv_sec * 1000000 + stop_time.tv_usec;
    float dis = (stop - start) / 1000000 * 34000 / 2;  //计算时间差求出距离
    return dis;
}

int main (void)
{
    float dis; 
    systemInit();
	// 每秒 测试一次距离并输出
    while(1){  
        dis = getDis();  
        printf("distance = %0.2f cm\n",dis);  
        delay(1000);  
    }  
	return 0;
}
